﻿#include "logger\LogManager.h"

#include <iostream>
#include <mutex>
#include <stdexcept>
#include <unordered_map>

// 核心依赖变为 BrokerLogger 和 LogBroker
#include "BrokerLogger.h"
#include "logger\LogBroker.h"

namespace Logging {
class LogManager::Impl {
 public:
  bool initialized = false;
  std::unordered_map<std::string, std::shared_ptr<ILogger>> loggers;
  std::mutex mutex;

  void initialize_impl() {
    std::lock_guard<std::mutex> lock(mutex);
    if (initialized) {
      return;
    }
    initialized = true;

    // 可以选择在这里预先创建一个默认 logger 来记录初始化信息
    get_logger_unlocked("default")->info("LogManager Initialized.");
  }

  void shutdown_impl() {
    std::lock_guard<std::mutex> lock(mutex);
    if (!initialized) {
      return;
    }

    // 在清空 logger 之前通知 Broker 和 Sinks 关闭
    get_logger_unlocked("default")->info("LogManager Shutting Down.");
    LogBroker::GetInstance().Shutdown();

    loggers.clear();
    initialized = false;
  }

  std::shared_ptr<ILogger> get_logger_impl(const std::string &name) {
    std::lock_guard<std::mutex> lock(mutex);
    if (!initialized) {
      throw std::logic_error(
          "LogManager::get_logger() called before LogManager::initialize().");
    }
    return get_logger_unlocked(name);
  }

 private:
  // 无锁的内部版本，供其他已加锁的成员函数调用
  std::shared_ptr<ILogger> get_logger_unlocked(const std::string &name) {
    auto it = loggers.find(name);
    if (it != loggers.end()) {
      return it->second;
    }

    // 逻辑极大简化：总是创建 BrokerLogger
    auto new_logger = std::make_shared<BrokerLogger>(name);
    loggers[name] = new_logger;
    return new_logger;
  }
};

// --- LogManager 的静态和 PIMPL 实现部分保持不变 ---
LogManager::LogManager() : pimpl_(std::make_unique<Impl>()) {}
LogManager::~LogManager() = default;

LogManager &LogManager::instance() {
  static LogManager manager_instance;
  return manager_instance;
}

void LogManager::initialize() { instance().pimpl_->initialize_impl(); }

void LogManager::shutdown() { instance().pimpl_->shutdown_impl(); }

std::shared_ptr<ILogger> LogManager::get_logger(const std::string &name) {
  return instance().pimpl_->get_logger_impl(name);
}

// register_backend 函数已彻底移除
}  // namespace Logging